/**
 *****************************************************************************
 * DESC ：. 
 * Author : Junwei Zhang 
 * CREATEDATE ：2012-7-10 
 * MODIFYLIST ：       	Name 			 Date 			Reason/Contents
 * 				------------------------------------------------------ 
 * 				 	Junwei Zhang     2012-7-10		Created.
 ****************************************************************************
 **/
package com.me.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * 
 * <br/>
 * 上午8:21:10 2012-7-10
 * 
 * @Author <a href="mailto:mestudying@sina.com">Junwei Zhang</a><br/>
 **/
public class JTalkServerThread extends Thread {
	public JTalkServer parent = null;
	public Socket socket = null;
	private PrintWriter out = null;
	private BufferedReader in = null;
	private boolean hasValidMemberConnection = false;

	public JTalkServerThread(JTalkServer parent, Socket socket) {
		this.setName("JTalkServerThread-" + socket.getPort());
		this.parent = parent;
		this.socket = socket;
		try {
			out = new PrintWriter(socket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		JTalkProtocal protocal = new JTalkProtocal(this);
		/** 接收客户端第一次连接的消息 */
		String inputLine = null;
		String messageOutput = protocal.processInput(null);
		out.println(messageOutput);
		try {
			/** 接收客户端发送的其它消息 */
			while ((inputLine = in.readLine()) != null) {
				System.out.println("----【Server Recv】:" + inputLine);
				messageOutput = protocal.processInput(inputLine);
				System.out.println("------【Server Send】:-----" + messageOutput);
				out.println(messageOutput);
				
				if (protocal.closeConnectionNow) {
					this.closeConnection();
					return;
				}

				if (this.getMember() != null) {
					this.getMember().setThread(this);
					if (!this.hasValidMemberConnection) {
						this.parent.sendUpdateRequestToAll(null);
						this.hasValidMemberConnection = true;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.closeConnection();
	}

	/**
	 * 获取此线程对应的登录用户.
	 * 
	 * @return
	 */
	public JTalkerMember getMember() {
		return this.parent.getMember(this.socket);
	}

	/**
	 * 向客户端发送消息.
	 * 
	 * @param message
	 */
	public void sendClientMessage(String message) {
		out.println(message);
	}

	/**
	 * Close connection and release OS resource.
	 */
	private void closeConnection() {
		try {
			this.out.close();
			this.in.close();
			if(this.getMember() != null){
				System.out.println("----【Server Msg】- DISCONNECT:  " + this.getConnectionInfo());
				System.out.println("----【Server Msg】- MEMBER logout: " + this.getMember().getUserInfo());
				System.out.println("----【Server Msg】- Number of connected members: " + (this.parent.getNumOfMembers() - 1));
				this.parent.removeMember(this.getMember().getUserPort());
			}
			this.socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		this.parent.sendUpdateRequestToAll(null);
	}

	/**
	 * 链接信息.
	 * @return
	 */
	private String getConnectionInfo() {
		String retVal = "TCP/IP: " + this.socket.getInetAddress();
		retVal += ":" + this.socket.getPort();
		return retVal;
	}

	/**
	 * Send the update request.
	 */
	public void sendUpdateRequest() {
		// TODO Auto-generated method stub
		String message = "<JTALKER><" + MessageParser.MESSAGE
				+ " content=\"[UPDATE] You have new messages.\" type=\"update\"/></JTALKER>";
		System.out.println("----【Server Send】:" + message);
		this.out.println(message);
	}

}
